require 'active_record/vendor/mysql'
require 'fasterCSV'

class TableToCsv 
	
	def create_new_connection(database)
		new_connection  = Mysql.new('localhost', 'root','',"#{database}")
		return new_connection
	end
	
	def get_table_data_to_csv(database)
		table_counter = 0
		new_connection = create_new_connection(database)
		all_table_names = new_connection.query('show tables')
		@start_time_database = Time.new
		all_table_names.each do |table_name|
			@start_time = Time.now 
			file_handler = File.new("#{table_name}.csv",'w')
			@data_from_each_row = new_connection.query("select * from #{table_name}")
			@data_from_each_row.each do |data_record|
				for single_field_value in 0..data_record.length-1
					if single_field_value != data_record.length-1
						file_handler.write(data_record[single_field_value]+",")
					else
						file_handler.write(data_record[single_field_value])
					end
				end	
				file_handler.write("\n")
			end
			@end_time = Time.now
			generate_extraction_info_file_table_level(new_connection,"#{table_name}", @start_time,@end_time)
			table_counter = table_counter + 1
		end
		@end_time_database = Time.new
		generate_extraction_info_file_database_level(database,table_counter,(@end_time_database - @start_time_database))
	end		
	
	def generate_extraction_info_file_table_level(connection,names,start_time,end_time)
		row_counter = 0
		time_required_for_this_table = end_time - start_time,
		total_number_of_rows = connection.query("select * from #{names}")
		total_number_of_rows.each do |row|
				row_counter = row_counter + 1
			end
		file_handler = File.new("extraction statistics #{names}.txt",'w')
		file_handler.write('The table name is ')
		file_handler.write(names)
		file_handler.write("\n")
		file_handler.write('The extraction time required for this table ')
		file_handler.write(time_required_for_this_table)
		file_handler.write("\n")
		file_handler.write('The total number of records extracted ')
		file_handler.write(row_counter)
		file_handler.write("\n")
		file_handler.close
	end	
	
	def generate_extraction_info_file_database_level(database,total_tables,total_time_for_extraction)
		file_handler = File.new("extraction statistics #{database}.txt",'w')
		file_handler.write('Total number of tables extracted')
		file_handler.write(total_tables)
		file_handler.write("\n")
		file_handler.write('The total time required')
		file_handler.write(total_time_for_extraction)
		file_handler.write("\n")
		file_handler.close
	end	
	
end	
		
convert_to_csv = TableToCsv.new

#Just change the database name to the desired database which you want to extract
convert_to_csv.get_table_data_to_csv('summer_development')	


